var CacheController = BaseController.extend({
	cache : {} ,
	events : [] ,
	init: function(scope){
		this._super(scope)
		this._bindEvents();
	},
	_bindEvents : function(){
		for( var i = 0 ; i < this.events.length ; i++) {
			var event = this.events[i];
			this.$scope[event] = this[event].bind(this);	
		}
	} ,
	addData : function(key , value ){
		this.cache[key] = value;
	}  ,
	getData : function(key) {
		return this.cache[key] ;
	}
});

var AlumniDispalyCommand = Class.extend({
	command : function(arr){
		if( !arr  || arr.length == 0) {
			return this.filter();
		}
		if( arr.length == 1) {
			return this.one();
		}
		if( arr.length > 1) {
			return this.mul();
		}
	} ,
	filter : function(){
		return { edit : false , del : false , create : true  };
	} ,
	one : function() {
		return  { edit : true , del : true , create : false  }
	} ,
	mul : function() {
		return  { edit : false , del : true , create : false }
	}	
});

var FilterInfo = Class.extend({
	init: function(defs , data){
		this.fields = [];
		this.data = data || [];
		this.fieldDefs = defs || [];
		this.initFields();
	},
	initFields : function(){
		if( this.data.length > 0) { 
			for( var i = 0 ; i < this.fieldDefs.length ; i++) {
				var def = this.fieldDefs[i];
				if(def.type && def.type != '') {
					this[def.type](def);
				} 
				this.fields.push(def);
			}
		}
	} ,
	refresh : function(data) {
		this.data = data || [];
		this.fields = [];
		this.initFields();
	} ,
	getTitle : function(def , value){
		var alias = {};
		if( def && def.alias ) {
			alias = def.alias;
		}
		return alias && alias[value] ? alias[value] : value;
	} ,
	group : function(def ) {
		var data = this.data ;
		var group = jlinq.from(data).group(def.key);
		def.items = [];
		if( !def.lazy) {
			for(var k in group) {
				def.items.push({
					value : k , 
					title : this.getTitle(def , k)
				});
			}
		}
	} ,
	year : function( col ) {
		col.items = [];
		var data = this.data ;		
		var begin = jlinq.from(data).min(col.key)[col.key];
		var end = jlinq.from(data).max(col.key)[col.key];
		if( !begin) {
			var group = jlinq.from(data).group(col.key);
			for(var k in group) {
				if( k > 0 ) {
					begin = k;
					break;
				}
			}
			if( !begin ) {
				begin = 1990;
			}
		} 
		if( end == 0) {
			end = begin;
		}
		
		var num = end - begin;
		if( num == 0 ) {
			col.items.push({
				value :  [end - col.step , end + 1] , 
				title : (end - col.step) + '-' + end
			});
		} else {
			var step = num / col.step + 1;
			for(var j = 1 ; j < step ; j++ ) {
				col.items.push({
					value : [begin + (j-1)*col.step - 1 , begin + j*col.step + 1]  , 
					title : (begin + (j-1)*col.step) + '-' + (begin + j*col.step)
				}); 
			}
		}
	} ,
	expands : function(fieldNames , data){
		if( !fieldNames || fieldNames.length == 0 || !data  || data.length == 0) {
			return;
		}
		for( var i = 0 ; i < this.fields.length ; i++) {	
			var field = this.fields[i];
			for (var j = 0;  j < fieldNames.length ; j++ ) {
				if( field['key'] == fieldNames[j] ) {
					this.expand(field , data);
				}
			}
		}
	} , 
	expand : function(field , data){
		var group = jlinq.from(data).group(field.key);
		field.items = [];
		for(var k in group) {
			field.items.push({
				value : k , 
				title : this.getTitle(field , k)
			});
		}
	} ,
	click : function( info , col , data) {
		var type = info.type;
		var result = [];
		if(type && type == 'group' ) {
			if( info['expand'] ) {
				var groupData = jlinq.from(data).group(info.key)[col.value];
				this.expands( info['expand'] , groupData);
			}
		}
		info['value'] = col.value;
		info['clicked'] = col.title;
		result = this.getData(data);
		return result;
	}  , 
	getData : function(data) {
		var result = [];
		var from = jlinq.from(data);
		for( var i = 0 ; i < this.fields.length ; i++) {
			var field = this.fields[i];
			if( field.value ) {
				if( field.type == 'year') {
					from.between(field.key , field.value[0] , field.value[1]);
				} else {
					from.match(field.key , field.value);
				}
			} 
		}
		return from.select();
	} , 
	getSelectedConditions : function(){
		var selectedConditions = [];
		var noSelectedConditions = [];
		for( var i = 0 ; i < this.fields.length ; i++) {
			var field = this.fields[i];
			if( field.value ) {
				selectedConditions.push(field);
			} else {
				noSelectedConditions.push(field);
			}
		}
		return selectedConditions;

	} ,
	cancelSelected : function(field){
		field.value = null;
		field.clicked = null;
	}
});

var Combination = Class.extend({
	init : function(fields){
		this.fields = fields || []; 
		this.type = "";
	} , 
	addType : function(name) {
		var fields = this.fields;
		for (var i = 0 ; i < fields.length; i++) {
			if( name == fields[i].name) {
				this.type = fields[i].type;
			}
		}
	}
});

var CombinationFactory = Class.extend({
	init : function( options ) {
		this.instances = [];
		this.cond = {};
		this.options = options;
		this.instances.push(new Combination(options));
	} ,
	add : function(){
		this.instances.push(new Combination(this.options));
	}  , 
	minus : function(index , name) {
		delete this.cond[name];
		var ins = this.instances;
		this.instances = [];
		for(var i = 0 ; i < ins.length ; i++) {
			if( i != index) {
				this.instances.push(ins[i]);
			}
		}
	} ,
	change : function(event , name){
		this.cond[name] = event.target.value;
	}
});

var AlumniIndexController = CacheController.extend({

	_alimniModel : null,
	$filter : null ,
	events : ['selected' , 'loadURL' , 'edit' , 'remove' , 
	          'query' , 'advancedQuery' , 'enterKeyup' , 'customFilterClick'] ,
	command : new AlumniDispalyCommand() ,
	init : function($scope,  $filter , alumniModel , lazyAlumniService) {
		this._alimniModel = alumniModel;
		this.$filter = $filter;
		this.lazyAlumniService = lazyAlumniService;
		this._super($scope)
	},
	defineScope : function() {
		this.$scope.selectedData = {};
		this.$scope.$watch('selectAll' , this.selectedAll.bind(this));
		this.$scope.display = this.command.command();


		var columnDefs = [ 
			{ field : 'personalInfoName', displayName : '姓名', sortable : true, show : true , type : 'link' }, 
			{ field : 'personalInfoLocationCity', displayName : '所在地', sortable : true, show : true }, 
			{ field : 'personalInfoContactCellphoneNumber', displayName : '手机', sortable : true, show : true}, 
			{ field : 'personalInfoEmail', displayName : '邮箱', sortable : true, show : false}, 
			{ field : 'educationInfoMajor', displayName : '专业', sortable : true, show : false}, 
			{ field : 'workInfoCompanyName', displayName : '单位名称', sortable : true, show : true}, 
			{ field : 'alumniAssociationName', displayName : '所属校友会', sortable : true, show : true}, 
			{ field : 'alumniAssociationPosition', displayName : '校友会职务', sortable : true, show : false }
		];
		this.$scope.alumnuiTable = new DataTable(columnDefs);
	
		var fileds = [
		    { name : 'name' , title : '姓名' } ,
		    { name : 'usedName' , title : '曾用名' } ,
		    { name : 'origin' , title : '籍贯' } ,
		    { name : 'nation' , title : '民族' } ,
		    { name : 'politicalStatus' , title : '政治面貌' } ,
		    { name : 'location' , title : '所在地' } ,
		    { name : 'studentId' , title : '学号' } ,
		    { name : 'enrollmentTime' , title : '入学年份' , type : 'timeRange' } ,
		    { name : 'graduationTime' , title : '毕业年份' , type : 'timeRange'  } ,
		    { name : 'department' , title : '院系' } ,
		    { name : 'major' , title : '专业' } ,
		    { name : 'className' , title : '班级' } ,
		    { name : 'educationQuality' , title : '学历' } ,
		    { name : 'degree' , title : '学位' } ,
		    { name : 'schoolingSpan' , title : '学制' } ,
		    { name : 'enrollType' , title : '培养方式' } ,
		    { name : 'companyName' , title : '单位名称' } ,
		    { name : 'companyType' , title : '单位性质' } ,
		    { name : 'industry' , title : '单位行业' } ,
		    { name : 'position' , title : '职务名称' } ,
		    { name : 'association' , title : '所属校友会' } ,
		    { name : 'associationPosition' , title : '校友会职务' }
		];
		this.$scope.comb = new CombinationFactory(fileds);
		var filterOptions = [
			{ key : 'alumniAssociationName' , title : '校友会' , type : 'group'} ,
			{ key : 'educationInfoDepartment' , title : '院系', type : 'group' , expand : ['educationInfoMajor']} ,
			{ key : 'educationInfoMajor' , title : '专业' ,  type : 'group' , lazy : true } ,
//			{ key : 'educationInfoDateBegin' , title : '入学年份', type : 'year' , step : 4 },
			{ key : 'educationInfoDateEnd' , title : '毕业年份', type : 'year' , step : 4 },
			{ key : 'personalInfoLocationCity' , title : '所在地' , type : 'group'} ,
//			{ key : 'personalInfoGendar' , title : '性别' , type : 'group' , alias : {MALE:'男' , FEMALE : '女'}} ,
//			{ key : 'personalInfoAlive',title : '在世', type:'group', alias : {'TRUE':'是','FALSE': '否'}}
		];


		var pagination = new LazyPagination( { 
			lazyLoading : function(type){
				this.lazyAlumniService[type](function(data){
					console.log(data);
					console.log(this);
				});
			}.bind(this)
		});

		this.$scope.pagination = pagination;
		this.$scope.dataTable = new LazyDataTable(columnDefs);
		this.$scope.filterInfo =  new FilterInfo(filterOptions);
	},
	customFilterClick : function(info , col){
		var data = this.$scope.filterInfo.click(info , col , this.cache.alumni);
		this.$scope.alumnuiTable.data = data;
	} ,
	loadURL : function(url){
		location.href = url;
	} ,
	selected : function(event){
		var checkedbox = event.target;		
		if( checkedbox.checked ) {
			this.$scope.selectedData[checkedbox.value] = checkedbox.value;
		} else {
			delete this.$scope.selectedData[checkedbox.value];
		}
		this.$scope.display = this.command.command(this.getSelectedAllData());
	} ,
	selectedAll : function(){
		if(!this.$scope.filteredAlumnui) {
			return ;
		}
		for(var i = 0 ; i < this.$scope.filteredAlumnui.length ; i++) {
			var val = this.$scope.filteredAlumnui[i];
			if( this.$scope.selectAll ) {
				this.$scope.selectedData[val.alumusId] = val.alumusId;
			} else {
				delete this.$scope.selectedData[val.alumusId]
			}
		}
		this.$scope.display = this.command.command(this.getSelectedAllData());
	} ,
	getSelectedAllData : function(){
		var arr = [];
		angular.forEach(this.$scope.selectedData ,  function(k){
			arr.push(k);
		});
		return arr;
	} ,
	edit : function(url){
		var arr = this.getSelectedAllData();
		if( arr.length == 1 ) {
			this.loadURL( url + "/" + arr[0] );
		}
	} ,
	remove : function(){
		var arr = this.getSelectedAllData();
		if( arr.length > 0 ) {
			for( var i =0 ; i < arr.length ; i++) {
				this._alimniModel.remove( arr[i]);
			}
		}
	} ,
	enterKeyup : function(event){
		if( event.keyCode == 13) {
			this.query();
		}
	} ,
	query : function() {
		if(!this.$scope.keyword) {
			return ;
		}
		// this._alimniModel.search(this.$scope.keyword , function(data) {
		// 	this.refreshView(data.alumni);
		// 	console.log('ok!');
		// }.bind(this) , function(){
		// 	console.log('error');
		// } )

		this.lazyAlumniService.search((this.$scope.keyword , function(data) {
			this.refreshView(data.alumni);
			// var ids = data.id.split(",");
			this.$scope.pagination.load(data.alumni , data.total , ids[0] , ids[1] );
		}.bind(this));
	} ,
	advancedQuery : function(){
		this._alimniModel.advancedSearch(this.$scope.comb.cond , function(data) {
			this.refreshView(data);
		}.bind(this));
	} ,
	refreshView : function(data) {
		this.cache.alumni = data;
		this.$scope.alumnuiTable.data = data;
		this.$scope.filterInfo.refresh(data);
	}
})

AlumniIndexController.$inject = [ '$scope' , "$filter", 'AlumniModel' , 'LazyAlumniService'];